package tool;

import java.util.HashMap;
import java.util.Map;

/**
 * A class caching energy height data from file user uploaded. It is a singleton
 * class that you should use <code>getInstance()</code> method to get the access
 * to the instance.
 */
public class Cache {
	
	/**
	 * Internal class to wrap <code>float</code> data.
	 */
	private class Float2D {
		
		/** 2D float data */
		private float[][] data;
		
		/**
		 * Constructor method.
		 * 
		 * @param data 2D float data
		 */
		public Float2D(float[][] data){
			this.data = data;
		}
		
		/**
		 * Get 2D float data.
		 * 
		 * @return 2D float data
		 */
		public float[][] getData(){
			return data;
		}
	}
	
	/** the instance of this singleton class */
	private static Cache instance;
	
	/** 
	 * hash map for cache 2D float data, the key is the name of the file 
	 * user uploaded 
	 */
	private Map<String, Float2D> map;
	
	/**
	 * Get the instance of this singleton class.
	 * 
	 * @return the instance of this singleton class
	 */
	public static Cache getInstance(){
		if(instance == null){
			instance = new Cache();
		}
		
		return instance;
	}
	
	/**
	 * Cache the 2D float data with its uploaded filename.
	 * 
	 * @param filename the name of the file user uploaded
	 * @param data 2D float data
	 */
	public void put(String filename, float[][] data){
		map.put(filename, new Float2D(data));
	}
	
	/**
	 * Get the cached 2D float data by filename, and then remove it from cache.
	 * 
	 * @param filename the name of the file user uploaded
	 * 
	 * @return 2D float data
	 */
	public float[][] fetch(String filename){
		return map.remove(filename).getData();
	}
	
	/**
	 * Constructor method, declared private to avoid codes accessing to the instance
	 * by calling <code>new</code> method.
	 */
	private Cache(){
		map = new HashMap<String, Float2D>();
	}
	
}
